package com.hunter.jerrymouse.util;

import com.hunter.jerrymouse.response.Response;

import java.io.*;

/**
 * Created by hunter
 * <p>
 * 文件写出流工具
 */
public class FileUtils {

    public static void write(String filePath, Response response) throws IOException {
        write(new File(filePath), response);
    }

    public static void write(String filePath, String writeFileName, Response response, boolean keepAlive) throws IOException {
        write(new File(filePath), writeFileName, response, keepAlive);
    }

    public static void write(File file, Response response) throws IOException {
        write(file, file.getName(), response, false);
    }

    public static void write(File file, String writeFileName, Response response, boolean keepAlive) throws IOException {
        if (!file.exists()) {
            throw new FileNotFoundException();
        } else if (file.isDirectory()) {
            throw new IOException("Request file path is a direct");
        }
        response.addHeader("content-length", String.valueOf(file.length()));
        response.addHeader("content-type", "application/octet-stream");
        response.addHeader("content-disposition", String.format("attachment; filename=\"%s\"", writeFileName));
        if (keepAlive) {
            response.addHeader("connection", "keep-alive");
        }

        InputStream is = new FileInputStream(file);
        int tempLength = 1024;
        int readLength;
        byte[] bytes = new byte[tempLength];
        while ((readLength = is.read(bytes, 0, tempLength)) != -1) {
            response.write(bytes, 0, readLength);
        }

        response.flush();
        response.close();
    }
}
